#ifndef __M_BUF_H__
#define __M_BUF_H__
#include <vector>
#include <cassert>
namespace TopLog
{
#define BUFFER_SIZE (1 * 1024 * 1024)
#define THRESHOLD_BUFFER_SIZE (5 * 1024 * 1024)
#define LINER_BUFFER_SIZE (1 * 1024 * 1024)

    class Buffer
    {
    public:
        Buffer() : _buffer(BUFFER_SIZE), _read_idx(0), _write_idx(0){};
        // 插入数据
        void push(const char *data, size_t len)
        {
            // 缓冲区扩容
            // 1.固定大小，直接返回
            // if (BUFFER_SIZE < len)
            //     return;
            // 2.动态空间
            resize(len);
            // 1.把数据copy到vector里
            std::copy(data, data + len, &_buffer[_write_idx]);
            // 2.数据偏移
            moveWriter(len);
        }
        // 读大小
        size_t readAbleSize()
        {
            return (_write_idx - _read_idx);
        }
        size_t writeAbleSize()
        {
            return (_buffer.size() - _write_idx);
        }
        // 移动读指针
        void moveReader(size_t len)
        {
            assert(len <= readAbleSize());
            _read_idx += len;
        }
        // 重置
        void reset()
        {
            _write_idx = 0;
            _read_idx = 0;
        }
        // 交换地址
        void swap(Buffer &Buffer)
        {
            _buffer.swap(Buffer._buffer);
            std::swap(_write_idx, Buffer._write_idx);
            std::swap(_read_idx, Buffer._read_idx);
        }

        // 获取读起始位置
        const char *begin()
        {
            return &_buffer[_read_idx];
        }
        bool empty()
        {
            return _write_idx == _read_idx;
        }

    protected:
        void moveWriter(size_t len)
        {
            assert(len + _write_idx <= _buffer.size());
            _write_idx += len;
        }
        // 扩容
        void resize(size_t len)
        {
            if (len < writeAbleSize())
                return;
            size_t new_size = 0;
            if (len < THRESHOLD_BUFFER_SIZE)
            {
                new_size = _buffer.size() * 2 + len;
            }
            else
            {
                new_size = _buffer.size() + LINER_BUFFER_SIZE + len;
            }
            _buffer.resize(new_size);
        }

    private:
        std::vector<char> _buffer;
        size_t _read_idx;
        size_t _write_idx;
    };
}
#endif